package com.xiaotu.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;

@SuppressWarnings("deprecation")
public class HttpUtils
{

    private static final Logger logger = LoggerFactory
            .getLogger(HttpUtils.class);

    public static int TIMEOUT = 1000;// 超时时间，单位ms

    private static RequestConfig getRequestConfig()
    {
        RequestConfig.Builder builder = RequestConfig.custom();
        builder.setConnectionRequestTimeout(TIMEOUT).setConnectTimeout(TIMEOUT)
                .setSocketTimeout(TIMEOUT);
        return builder.build();
    }

    /**
     * 发送get请求 获取jsonp数据
     *
     * @param url 路径
     * @return
     */
    public static String httpGetJSONP(String url)
    {
        // get请求返回结果
        String strResult = "";
        try
        {
            HttpClient client = new DefaultHttpClient();
            // 发送get请求
            logger.info("get url:" + url);
            HttpGet request = new HttpGet(url);
            request.setConfig(getRequestConfig());

            // HttpResponse response = httpClientExecute(client, request);
            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                HttpEntity entity = response.getEntity();
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null)
                {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++)
                    {
                        if (codecs[i].getName().equalsIgnoreCase("gzip"))
                        {
                            response.setEntity(new GzipDecompressingEntity(
                                    response.getEntity()));
                        }
                    }
                }
                /** 读取服务器返回过来的json字符串数据 **/
                strResult = EntityUtils.toString(response.getEntity());
            }
            else
            {

                logger.error("get请求提交失败[code={}]:{}",
                        response.getStatusLine().getStatusCode(), url);
            }
        }
        catch (Exception e)
        {
            logger.error("url:{}", url);
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new SpiderException(SpiderExceptionCode.HttpIOException,
                    e.getMessage());
        }
        return strResult;
    }

    public static String httpPostJSONP(String url, Map<String, String> map)
    {
        // get请求返回结果
        String strResult = "";
        try
        {
            HttpClient client = new DefaultHttpClient();
            // 发送get请求
            logger.info("get url:" + url);
            HttpPost request = new HttpPost(url);
            request.setConfig(getRequestConfig());


            //设置参数
            List<NameValuePair> list = new ArrayList<>();
            for (Map.Entry<String, String> entry : map.entrySet())
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

            if (list.size() > 0)
            {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
                request.setEntity(entity);
            }


            // HttpResponse response = httpClientExecute(client, request);
            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                HttpEntity entity = response.getEntity();
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null)
                {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++)
                    {
                        if (codecs[i].getName().equalsIgnoreCase("gzip"))
                        {
                            response.setEntity(new GzipDecompressingEntity(
                                    response.getEntity()));
                        }
                    }
                }
                /** 读取服务器返回过来的json字符串数据 **/
                strResult = EntityUtils.toString(response.getEntity());
            }
            else
            {

                logger.error("get请求提交失败[code={}]:{}",
                        response.getStatusLine().getStatusCode(), url);
            }
        }
        catch (Exception e)
        {
            logger.error("url:{}", url);
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new SpiderException(SpiderExceptionCode.HttpIOException,
                    e.getMessage());
        }
        return strResult;
    }
    
    /**
     * 发送get请求 获取jsonp数据
     * @param url    路径  
     * @return
     */
    @SuppressWarnings("resource")
	public static String httpGetJSONP(String url,Map<String, String> headers){
        //get请求返回结果
    	String strResult ="";
        try {
            HttpClient client = new DefaultHttpClient();
            //发送get请求
            logger.info("get url:"+url);
            HttpGet request = new HttpGet(url);
            request.setConfig(getRequestConfig());
            if (headers != null) {
                for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
                    request.addHeader(headerEntry.getKey(), headerEntry.getValue());
                }
            }
            HttpResponse response = client.execute(request);
            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            	HttpEntity entity = response.getEntity();  
            	Header ceheader =entity.getContentEncoding();  
                if (ceheader != null) {  
                    HeaderElement[] codecs = ceheader.getElements();  
                    for (int i = 0; i < codecs.length; i++) {  
                        if (codecs[i].getName().equalsIgnoreCase("gzip")) {  
                            response.setEntity( new GzipDecompressingEntity(response.getEntity()));   
                        }  
                    } 
                }  
                /**读取服务器返回过来的json字符串数据**/
                strResult = EntityUtils.toString(response.getEntity());
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (Exception e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return strResult;
    }
    
    /**
     * 发送get请求 获取jsonp数据 utf-8
     *
     * @param url 路径
     * @return
     */
    public static String httpGetJSONPUTF(String url)
    {
        // get请求返回结果
        String strResult = "";
        try
        {
            HttpClient client = new DefaultHttpClient();
            // 发送get请求
            logger.info("get url:" + url);
            URIBuilder uri = new URIBuilder(url);
            HttpGet request = new HttpGet(uri.build());
            request.setConfig(getRequestConfig());
            //设置请求的报文头部的编码
            request.setHeader(
                new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
            //设置期望服务端返回的编码
            request.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));

            // HttpResponse response = httpClientExecute(client, request);
            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                HttpEntity entity = response.getEntity();
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null)
                {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++)
                    {
                        if (codecs[i].getName().equalsIgnoreCase("gzip"))
                        {
                            response.setEntity(new GzipDecompressingEntity(
                                    response.getEntity()));
                        }
                    }
                }
                /** 读取服务器返回过来的json字符串数据 **/
                strResult = EntityUtils.toString(response.getEntity(), "utf-8");
            }
            else
            {

                logger.error("get请求提交失败[code={}]:{}",
                        response.getStatusLine().getStatusCode(), url);
            }
        }
        catch (Exception e)
        {
            logger.error("url:{}", url);
            logger.error(ExceptionUtils.getStackTrace(e));
            throw new SpiderException(SpiderExceptionCode.HttpIOException,
                    e.getMessage());
        }
        return strResult;
    }
    
    //链接目标url
  	public static Connection connent(String url) {
  		//忽略https证书的再请求
  		HttpsUrlValidator.retrieveResponseFromServer(url); 
      	Connection conn = Jsoup.connect(url)    
	      .userAgent("Mozilla/5.0 (Windows NT 6.1; rv:47.0) Gecko/20100101 Firefox/47.0") // http请求的浏览器设置
	      .timeout(5000)   // http连接时长
	      .maxBodySize(0)
	      .method(Connection.Method.GET);
	      //.cookie("cookie", PropertiesUtil.getProperty("DouBanTVNotBrd.site.Cookie"));  	
      	return conn;
  	}

}
